<template>
  <div class="h-full flex flex-col" style="height: 82vh">
    <div class="flex justify-between mb-2">
      <div v-if="isOnline">在线</div>
      <div v-else>
        <span>{{ statusMsg }}</span>
        <i class="pi pi-replay ml-2" :class="connectLoading ? 'pi-spin': ''" style="font-size: 1rem"
           @click="connectServer"></i>
      </div>
      <div>被动模式</div>

      <div class="flex items-center">
        <span class="mr-2">我是服务器</span>
        <ToggleSwitch v-model="isServer" @change="serverAction"/>

      </div>
    </div>
    <!-- 聊天消息区域 -->
    <div class="flex-1 p-4 overflow-y-auto bg-gray-100">
      <div v-for="message in messages" :key="message.id" class="mb-4 flex items-end">
        <div v-if="message.type === 'text'" class="flex items-start">
          <div class="bg-blue-500 text-white p-2 rounded-lg flex">
            <p>{{ message.content }}</p>
          </div>
        </div>
        <div v-if="message.type.startsWith('image')" class="flex items-start">
          <div class="bg-blue-500 text-white p-2 rounded-lg max-w-xs">
            <Image :src="'http://' + server +message.download_url" alt="image" class="max-w-xs h-auto" preview/>
          </div>
        </div>
        <div v-else-if="message.type === 'file'" class="flex items-start">
          <div class="bg-blue-500 text-white p-2 rounded-lg max-w-xs">
            <p>{{ message.filename }}</p>
          </div>
        </div>
        <div>
          <Button v-if="message.type === 'file'" @click="downloadFile(message)" class="text-blue-300 mt-2" label="下载" size="small"
                  severity="info" variant="text"></Button>
          <i v-if="message.status === 'sending'" class="pi pi-spin pi-spinner ml-4" style="font-size: 1rem"></i>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="p-4 bg-gray-200">
      <!-- 文件预览区域 -->
      <div class="h-16 flex" v-if="files.length > 0">
        <div v-for="(file, index) in files" :key="index" class="file-item">
          <!-- 如果是图片文件，显示预览图 -->
          <div v-if="file.type.startsWith('image')" class="image-preview mr-2">
            <Image :src="file.preview" alt="Image" width="80"/>
          </div>
          <!-- 否则显示文件名称 -->
          <div v-else class="file-card">
            <span>{{ file.name }}</span>
          </div>
        </div>
      </div>

      <div class="flex">
        <InputText
            v-model="newMessageText"
            class="flex-1 mr-2"
            placeholder="输入消息..."
            @paste="handlePaste"
            @keydown.enter="sendMessage"
        />
        <Button label="发送" @click="sendMessage"/>
      </div>
    </div>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue';
import {v4 as uuidv4} from 'uuid';

const connectLoading = ref(false)
const statusMsg = ref('')
const connectStatus = ref(false)
const isServer = ref(false)
const isOnline = ref(false)
const server = ref('127.0.0.1:6986')
const files = ref([])
const newMessageText = ref(''); // 输入框的文本内容
const messages = ref([])


window.updateMessage = function (data) {
  let isOk = true
  console.log(data)
  for (let i = 0; i < messages.value.length; i++) {
    if (messages.value[i].msg_id === data.msg_id) {
      messages.value[i] = data
      if (data.download_url !== undefined && data.download_url !== '') {
        pywebview.api.open_dir(data)
      }
      isOk = false
      break
    }
  }

  if (isOk) {
    messages.value.push(data)
  }
}

// 发送消息并上传文件
function sendMessage() {
  const msg_id = uuidv4()
  if (newMessageText.value) {
    sendChatMessage({type: 'text', content: newMessageText.value}, msg_id);
  }
  // 检查是否有文件
  if (files.value.length > 0) {
    files.value.forEach(item => {
      sendChatMessage(item, msg_id);
    })
  }

  newMessageText.value = ''
  files.value = []
}


// 发送聊天消息
const sendChatMessage = async (text, msg_id) => {
  const message = {
    msg_id: msg_id,
    status: 'sending',
    type: text.type,
    content: text.content,
    preview: text.preview,
    filename: text.name,
    file: text.file,
  }
  messages.value.push(message)

  if (message.type === 'text') {
    await pywebview.api.send_message(message)

  } else {
    // 将文件上传到本地缓存
    const data = await uploadFile(message.file)

    await pywebview.api.send_message({
      msg_id: msg_id,
      status: 'sending',
      type: 'file',
      filename: text.name,
      filesize: data.file_size,
      filepath: data.download_url
    })
  }
  message.status = 'done'
}


// 处理粘贴事件
function handlePaste(event) {
  const clipboardItems = event.clipboardData.items;
  for (let i = 0; i < clipboardItems.length; i++) {
    const item = clipboardItems[i];
    // 判断是否为文件
    if (item.kind === 'file') {
      const file = item.getAsFile();
      // 将文件预览存储在文件对象中
      files.value.push({
        name: file.name,
        type: file.type,
        file: file
      });
    }
  }
  event.preventDefault(); // 防止浏览器默认的粘贴行为
}

// 处理下载文件
const downloadFile = async (message) => {
  // 动态创建一个下载链接
  await pywebview.api.download_file(message)


}

// 上传文件的函数
const uploadFile = async (file) => {
  const formData = new FormData();
  formData.append('file', file);
  try {
    const response = await fetch('http://' + server.value + '/upload/', {
      method: 'POST',
      body: formData
    });
    if (response.ok) {
      return await response.json();
    } else {
      console.error('文件上传失败');
    }
  } catch (error) {
    console.error('上传文件时出错:', error);
  }
}

const serverAction = async () => {
  if (isServer.value === true) {
    await pywebview.api.start_transport_server()
  } else {
    await pywebview.api.close_transport_server()
  }
}
</script>

<style scoped>
/* 自定义样式，如果需要进一步调整 */
</style>
